package com.example.mobile1931605061xhj0603;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private TextView tvMainTitle;
    private Button buttonPlayer;
    private Button btnMainPause;
    private Button btnMainRepalyer;
    private Button btnMainStop;
    private MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initMusic();
        buttonPlayer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer == null) {
                    mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.old_boy);
                }
                mediaPlayer.start();
            }
        });
        btnMainPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer.isPlaying()){
                    mediaPlayer.pause();
                }
            }
        });
        btnMainRepalyer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer!=null&&mediaPlayer.isPlaying()){
                    mediaPlayer.seekTo(0);
                    mediaPlayer.start();
                }
            }
        });
        btnMainStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer.isPlaying()){
                    mediaPlayer.stop();
                    mediaPlayer.release();
                    mediaPlayer=null;
                }
            }
        });
    }

    private void initMusic() {
        mediaPlayer = MediaPlayer.create(this, R.raw.old_boy);
    }

    private void initView() {
        tvMainTitle = (TextView) findViewById(R.id.tvMainTitle);
        buttonPlayer = (Button) findViewById(R.id.buttonPlayer);
        btnMainPause = (Button) findViewById(R.id.btnMainPause);
        btnMainRepalyer = (Button) findViewById(R.id.btnMainRepalyer);
        btnMainStop = (Button) findViewById(R.id.btnMainStop);
    }
}